#include "monitor.h"
#include "ui_monitor.h"
#include <QDebug>
#include <QMouseEvent>
#include <QFileDialog>
#include <QTimer>
#include <QCheckBox>
#include <QDateTime>
#include <QMessageBox>
#include <QMenu>

#include "osg/osgwidget.h"
#include "osg/basenode.h"

#include <osg/Material>
#include <osg/MatrixTransform>

#include "logindlg.h"

#include "mongo/userdata.h"

#include "plottemperature.h"
#include "plotpressure.h"
#include "ploto2.h"
#include "plottemperaturemonitor.h"

#include "dialoglasertest.h"

#include "logdialog.h"
#include "logfulldialog.h"
#include "log/log.h"

#include "slice/cliread.h"
#include "servo/servoagent.h"
#include "osg/osgdatamanager.h"
#include "plc/plcdataprocess.h"
#include "system/systemconfig.h"
#include "system/systemmonitor.h"
#include "system/taskagent.h"

Monitor::Monitor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Monitor),
    dateTime_(new QTimer(this)),
    osgWidget_(new OsgWidget),
    osgSet_(new OsgWidget),
    plotTemp_(new PlotTemperature),
    plotPressure_{new PlotPressure},
    plotO2_{new PlotO2},
    plotTempM_(new PlotTemperature),
    plotPressureM_{new PlotPressure},
    plotO2M_{new PlotO2},
    plotMicroPressure_{new PlotTemperatureMonitor},
    logDialogMini(new LogDialog(this)),
    logDialogFull(new LogFullDialog(this))
{
    ui->setupUi(this);
    ui->stackedWidget_main->setCurrentIndex(0);
    ui->tabWidget_Preparation->setCurrentIndex(0);
    ui->widget_head->setProperty("LEVEL","head");
    ui->widget_menu->setProperty("LEVEL","menu");
    ui->widget_work->setProperty("LEVEL","work");
    ui->widget_status->setProperty("LEVEL","status");
    QIcon icon(":/icon/icons/logo_taskbar.ico");
    QApplication::setWindowIcon(icon);

    //TODO 做个开机界面显示加载中，加载完毕退出

    connect(dateTime_, SIGNAL(timeout()), this, SLOT(displayCurrentTime()));
    dateTime_->start(1000);
    this->setWindowFlags(Qt::FramelessWindowHint);
    this->showNormal();
}

Monitor::~Monitor()
{
    delete ui;
    delete osgWidget_;
}

void Monitor::init()
{
    // init log
    HIM::Log::init();
    HIM::Log::attach(logDialogMini);
    HIM::Log::attach(logDialogFull);
    QHBoxLayout* Hlayout_log = new QHBoxLayout(ui->pushButton_Log);
    Hlayout_log->addWidget(logDialogMini);
    ui->pushButton_Log->setLayout(Hlayout_log);
    ui->hLayout_logFull->addWidget(logDialogFull);

    // init...
    QMenu *menu = new QMenu(ui->toolButton_more);
    QAction *actionLaserTest = menu->addAction(tr("laser test"));
    QAction *actionAbuot = menu->addAction(tr("about"));
    QAction *actionExit = menu->addAction(tr("exit"));

    ui->toolButton_more->setMenu(menu);
    ui->toolButton_more->setPopupMode(QToolButton::InstantPopup);

    connect(actionExit,SIGNAL(triggered()),this,SLOT(on_exit()));
    connect(actionLaserTest,SIGNAL(triggered()),this,SLOT(on_laserTest()));
    connect(actionAbuot,SIGNAL(triggered()),this,SLOT(on_about()));

    //init plot
    ui->VLayout_plotTemp->addWidget(plotTemp_);
    ui->hLayout_plotPressure->addWidget(plotPressure_);
    ui->hLayout_plotO2->addWidget(plotO2_);

    //init monitorPlot
    ui->horizontalLayout_monitor_BaseTemp->addWidget(plotTempM_);
    ui->horizontalLayout_monitor_CabinPressure->addWidget(plotPressureM_);
    ui->horizontalLayout_monitor_O2->addWidget(plotO2M_);
    ui->horizontalLayout_monitor_Mpressure->addWidget(plotMicroPressure_);

    //init osg
    OSGDATAMANAGER->init();
    ui->HLayout_osg->addWidget(osgWidget_->getOsgWidget());
    connect(osgWidget_,&OsgWidget::osgWidgetAlready,this,[=](){
        QRect r = ui->frame_osg->geometry();
        float aspectRatio = static_cast<double>(r.width()) / static_cast<double>(r.height());
        osgWidget_->getOsgWidget()-> getOsgViewer()->getCamera()->setProjectionMatrixAsPerspective(30.0, aspectRatio, 1.0, 1000000.0);
        osgWidget_->enableWheel(true);
    });

    osgWidget_->addToRoot(OSGDATAMANAGER->getBaseNode("Base300")->getBaseNode(),"Base300");
    osgWidget_->addToRoot(OSGDATAMANAGER->getSliceNode("SliceData")->getSliceNode(),"SliceData");

    ui->Layout_printPrepatation->addWidget(osgSet_->getOsgWidget());
    connect(osgSet_,&OsgWidget::osgWidgetAlready,this,[=](){
        QRect r = ui->widget_printPrepatation->geometry();
        float aspectRatio = static_cast<double>(r.width()) / static_cast<double>(r.height());
        osgSet_->getOsgWidget()-> getOsgViewer()->getCamera()->setProjectionMatrixAsPerspective(30.0, aspectRatio, 1.0, 1000000.0);
    });

    //osgSet_->addToRoot(OSGDATAMANAGER->getModelNode("Shell")->getModel(),"Shell");
    osgSet_->addToRoot(OSGDATAMANAGER->getModelNode("Scraper")->getModel(),"Scraper");
    osgSet_->addToRoot(OSGDATAMANAGER->getModelNode("Left")->getModel(),"Left");
    osgSet_->addToRoot(OSGDATAMANAGER->getModelNode("Core")->getModel(),"Core");
    osgSet_->addToRoot(OSGDATAMANAGER->getModelNode("Right")->getModel(),"Right");

    //init AllPara
    std::vector<std::pair<std::string,std::string>> NetworkInfos;
    if(SYSTEMMONITOR.getNetworkCordInfo(NetworkInfos)){
        for(auto i : NetworkInfos){
            ui->servoAdrName->addItem(QString::fromStdString(i.first)
                                      ,QString::fromStdString(i.second));
        }
    }else{
        HIM_ERROR(tr("Unable to obtain network card information, please check!").toStdString());
    }

    if(loadSysConfig()){
        QObjectList objectList = ui->tab_systemSet->children();
        objectList.append(ui->tab_ServoSet->children());
        objectList.append(ui->tab_LaserSet->children());

        for(auto it : objectList){
            if(it->metaObject()->className()==QString("QSpinBox")){
                auto value = SYSTEMCONFIG.getLongValue(PARAMETER,it->objectName().toStdString());
                dynamic_cast<QSpinBox*>(it)->setValue(value);
                connect(it, SIGNAL(valueChanged(int)), this, SLOT(onSysConfigChanged(int)));
            }else if(it->metaObject()->className()==QString("QDoubleSpinBox")){
                auto value = SYSTEMCONFIG.getDoubleValue(PARAMETER,it->objectName().toStdString());
                dynamic_cast<QDoubleSpinBox*>(it)->setValue(value);
                connect(it, SIGNAL(valueChanged(double)), this, SLOT(onSysConfigChanged(double)));
            }else if(it->metaObject()->className()==QString("QComboBox")){
                auto value = SYSTEMCONFIG.getValue(PARAMETER,it->objectName().toStdString());
                auto index = dynamic_cast<QComboBox*>(it)->findData(QString::fromStdString(value));
                if(-1!=index){
                    dynamic_cast<QComboBox*>(it)->setCurrentIndex(index);
                }else{
                    SYSTEMCONFIG.setValue(PARAMETER,it->objectName().toStdString(),
                                          dynamic_cast<QComboBox*>(it)->currentData().toString().toStdString());
                    SYSTEMCONFIG.saveFile(CONFIGPATH);
                }
                connect(it, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onSysConfigChanged(const QString &)));
            }else if(it->metaObject()->className()==QString("QLineEdit")){
                auto value = SYSTEMCONFIG.getValue(PARAMETER,it->objectName().toStdString());
                dynamic_cast<QLineEdit*>(it)->setText(QString::fromStdString(value));
                connect(it, SIGNAL(textChanged(const QString &)), this, SLOT(onSysConfigChangedLineEdit(const QString &)));
            }
        }

        ui->doubleSpinBox_ServoASpeed->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"lServoSpeed"));
        ui->doubleSpinBox_ServoBSpeed->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"rServoSpeed"));
        ui->doubleSpinBox_scraperSpeed->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"pcAxisMoveSpeed"));
        ui->doubleSpinBox_scraperCoverSpeed->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"pcAxisCoverSpeed"));

        ui->doubleSpinBox_scraperRatio->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"pcMulValue"));
        ui->doubleSpinBox_adjPowerRatio->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"pcMulValue"));

        ui->doubleSpinBox_oxygenContent->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"oxygenContent"));
        ui->doubleSpinBox_oxygenContentMax->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"oxygenContentMax"));
        ui->doubleSpinBox_AirRate->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"AirRate"));
        ui->doubleSpinBox_CabinPressureMax->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"CabinPressureMax"));
        ui->doubleSpinBox_CabinPressureMin->setValue(SYSTEMCONFIG.getDoubleValue(PARAMETER,"CabinPressureMin"));

        SYSTEMMONITOR.loadAllConfig();
    }

    connect(&SYSTEMMONITOR,&HIM::SystemMonitor::dataSynchronous,this,&Monitor::on_dataSynchronous);
    connect(this,&Monitor::initApp,&SYSTEMMONITOR,&HIM::SystemMonitor::on_initApp);
    connect(&TASKAGENT,&HIM::TaskAgent::updataCliShow,this,&Monitor::on_updataCliShow);
    connect(&TASKAGENT,&HIM::TaskAgent::printFinished,this,&Monitor::on_printFinished);
    HIM_INFO(tr("Software startup").toStdString());
    startTimestamp = QDateTime::currentSecsSinceEpoch();
    emit initApp();

    //#ifdef DEBUG
    //#else
    //#endif
}

void Monitor::displayCurrentTime()
{
    ui->label_time->setText(
                QDateTime::currentDateTime().toString("yyyy-MM-dd\n" "hh:mm:ss"));
    timeTick_S += 1;
}

/***monitor page select function***/
void Monitor::on_toolButton_load_clicked()
{
    ui->stackedWidget_main->setCurrentIndex(0);
}

void Monitor::on_tB_preparation_clicked()
{
    ui->stackedWidget_main->setCurrentIndex(1);
}

void Monitor::on_tB_print_clicked()
{
    ui->stackedWidget_main->setCurrentIndex(2);
}

void Monitor::on_tB_monitor_clicked()
{
    ui->stackedWidget_main->setCurrentIndex(3);
}

void Monitor::on_tB_Precodes_clicked()
{
    ui->stackedWidget_main->setCurrentIndex(4);
}

void Monitor::on_tB_log_clicked()
{
    ui->stackedWidget_main->setCurrentIndex(5);
}

void Monitor::on_toolButton_set_clicked()
{
    ui->stackedWidget_main->setCurrentIndex(6);
    ui->tabWidget_set->setCurrentIndex(0);
}

void Monitor::on_toolButton_logOn_clicked()
{
    if(role!="guest"){
        role = "guest";
        changeCurrentRole(GUEST);
    }else{
        LoginDlg* login= new LoginDlg(this);
        connect(login,SIGNAL(updatePermissions(QString)),this,SLOT(on_updatePermissions(QString)));
        login->exec();
        delete login;
    }
}

void Monitor::on_pushButton_Log_clicked()
{
    ui->tB_log->setChecked(true);
    ui->stackedWidget_main->setCurrentIndex(5);
}

void Monitor::on_toolButton_deviceStatus_clicked()
{
    ui->tB_monitor->setChecked(true);
    ui->stackedWidget_main->setCurrentIndex(3);
}

/***role login function***/
void Monitor::on_updatePermissions(QString account)
{
    role = QString::fromStdString(USERDATA_MOGO->getValue(ACCOUNT,account.toStdString(),USERDATA_MOGO->UserKeyLists[ROLE]));
    changeCurrentRole(UserMap[role]);
}

void Monitor::changeCurrentRole(UserId roleID)
{
    //TODO更新用户权限
    switch (roleID)
    {
    case ADMIN : {
        ui->label_RoleIcom->setPixmap(QPixmap(":/icon/icons/admin64x64.png"));
        ui->toolButton_logOn->setText(tr("[Log out]"));
        ui->label_RoleText->setText(tr("Hello,Admin"));
        HIM_INFO(tr("User changed to admin").toStdString());
        AdminPermissions();
    } break;
    case ENGINEER : {
        ui->label_RoleIcom->setPixmap(QPixmap(":/icon/icons/programmer_64x64.png"));
        ui->toolButton_logOn->setText(tr("[Log out]"));
        ui->label_RoleText->setText(tr("Hello,Engineer"));
        HIM_INFO(tr("User changed to engineer").toStdString());
        EngineerPermissions();
    } break;
    case OPERATOR : {
        ui->label_RoleIcom->setPixmap(QPixmap(":/icon/icons/engineer64x64.png"));
        ui->toolButton_logOn->setText(tr("[Log out]"));
        ui->label_RoleText->setText(tr("Hello,Operator"));
        HIM_INFO(tr("User changed to operator").toStdString());
        OperatorPermissions();
    } break;
    case GUEST :
    default : {
        ui->label_RoleIcom->setPixmap(QPixmap(":/icon/icons/user_b.png"));
        ui->toolButton_logOn->setText(tr("[Log on]"));
        ui->label_RoleText->setText(tr("Hello,Please"));
        HIM_INFO(tr("User changed to guest").toStdString());
        GuestPermissions();
    } break;
    }
}

void Monitor::GuestPermissions()
{

}

void Monitor::OperatorPermissions()
{

}

void Monitor::EngineerPermissions()
{

}

void Monitor::AdminPermissions()
{

}

/***more function***/
void Monitor::on_exit()
{
    int ret = QMessageBox::question(this, tr("Warning"),tr("Confirm exit?"),
                                    QMessageBox::Yes | QMessageBox::No);
    if(ret==QMessageBox::Yes){
        QCoreApplication::quit();
    }
}

void Monitor::on_laserTest()
{
    DialogLaserTest * dialogLaserTest= new DialogLaserTest(this);
    dialogLaserTest->exec();
    delete dialogLaserTest;
}

void Monitor::on_about()
{
    //TODO
    //about
}

/***osg function***/
void Monitor::on_pushButton_2D_clicked()
{
    osgWidget_->getOsgWidget()->getOsgViewer()->home();
    osgWidget_->enableMouse(false);
}

void Monitor::on_pushButton_3D_clicked()
{
    osgWidget_->enableMouse(true);
}

void Monitor::on_pushButton_backHome_clicked()
{
    osgWidget_->getOsgWidget()->getOsgViewer()->home();
}

/***synchronous function***/
void Monitor::on_dataSynchronous(QMap<int,float> syncMap)
{
    //qDebug()<<"on_dataSynchronous";
    //TODO 曲线图数据更新

    //TODO OSG伺服位置同步

    //TODO 数据存储
    int time{0};
    bool plotRefresh{false};
    if(timeTick_S == 10){
        qint64 currentTimestamp = QDateTime::currentSecsSinceEpoch();
        time = currentTimestamp - startTimestamp;
        plotRefresh = true;
        timeTick_S = 0 ;
    }

    for(auto it = syncMap.constBegin(); it != syncMap.constEnd() ; ++it){
        switch (it.key()) {
        case HIM::toolButton_deviceStatus : {
            if(it.value()>0){
                ui->toolButton_deviceStatus->setIcon(QIcon(":/icon/icons/lamp_error.png"));
                ui->toolButton_deviceStatus->setText(tr("abnormal"));
                PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_4,true);
                PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_4,false);

                if(TASKAGENT.stopPrintTask()){
                    QMessageBox::warning(this, tr("Print termination"),tr("system error!"),
                                         QMessageBox::Yes);
                };

            }else{
                ui->toolButton_deviceStatus->setIcon(QIcon(":/icon/icons/lamp_idle.png"));
                ui->toolButton_deviceStatus->setText(tr("normal"));
            }
        }break;
        case HIM::label_alarm_plcConn : {
            if(it.value()>0){
                ui->label_alarm_plcConn->setPixmap(QPixmap(":/icon/icons/light_error.png"));

                ui->label_statsusAirO2_o2->setPixmap(QPixmap(":/icon/icons/o2_err.png"));
                ui->label_statusSpeedFan_speed->setPixmap(QPixmap(":/icon/icons/speed_err.png"));
                ui->label_statusairsupplyvalve_pre->setPixmap(QPixmap(":/icon/icons/pressure_err.png"));
                ui->label_statusWashingvalvePressure_pre->setPixmap(QPixmap(":/icon/icons/pressure_err.png"));
                ui->label_statusBaseTemperature_temp->setPixmap(QPixmap(":/icon/icons/temperature_err.png"));
                ui->label_statusEnvTemperature_temp->setPixmap(QPixmap(":/icon/icons/temperature_err.png"));
            }else{
                ui->label_alarm_plcConn->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));

                ui->label_statsusAirO2_o2->setPixmap(QPixmap(":/icon/icons/o2.png"));
                ui->label_statusSpeedFan_speed->setPixmap(QPixmap(":/icon/icons/speed.png"));
                ui->label_statusairsupplyvalve_pre->setPixmap(QPixmap(":/icon/icons/pressure.png"));
                ui->label_statusWashingvalvePressure_pre->setPixmap(QPixmap(":/icon/icons/pressure.png"));
                ui->label_statusBaseTemperature_temp->setPixmap(QPixmap(":/icon/icons/temperature.png"));
                ui->label_statusEnvTemperature_temp->setPixmap(QPixmap(":/icon/icons/temperature.png"));
            }
        }break;
        case HIM::label_alarm_ethrrcatConn : {
            if(it.value()>0){
                ui->label_alarm_ethrrcatConn->setPixmap(QPixmap(":/icon/icons/light_error.png"));

                ui->label_statusServoPowder_moto->setPixmap(QPixmap(":/icon/icons/moto_err.png"));
                ui->label_statusServoFeed_moto->setPixmap(QPixmap(":/icon/icons/moto_err.png"));
                ui->label_statusServoMan_moto->setPixmap(QPixmap(":/icon/icons/moto_err.png"));
            }else{
                ui->label_alarm_ethrrcatConn->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));

                ui->label_statusServoPowder_moto->setPixmap(QPixmap(":/icon/icons/moto.png"));
                ui->label_statusServoFeed_moto->setPixmap(QPixmap(":/icon/icons/moto.png"));
                ui->label_statusServoMan_moto->setPixmap(QPixmap(":/icon/icons/moto.png"));
            }
        }break;
        case HIM::label_alarm_rtcConn : {
            if(it.value()>0){
                ui->label_alarm_rtcConn->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                ui->label_laserStatus_laser->setPixmap(QPixmap(":/icon/icons/laser_err.png"));
            }else{
                ui->label_alarm_rtcConn->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_laserStatus_laser->setPixmap(QPixmap(":/icon/icons/laser.png"));
            }
        }break;
        case HIM::label_alarm_mongoDBConn : {
            if(it.value()>0){
                ui->label_alarm_mongoDBConn->setPixmap(QPixmap(":/icon/icons/light_error.png"));
            }else{
                ui->label_alarm_mongoDBConn->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
            }
        }break;
        case HIM::label_alarm_fan : {
            if(it.value()>0){
                ui->label_alarm_fan->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                ui->label_alarm_loopClean->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                ui->label_loopCleanStatus->setText(tr("abnomal"));
                ui->label_statusSpeedFan_speed->setPixmap(QPixmap(":/icon/icons/speed_err.png"));
                ui->label_statusSpeedFan->setStyleSheet("QLabel{color:red;}");
            }else{
                ui->label_alarm_fan->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_alarm_loopClean->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_loopCleanStatus->setText(tr("nomal"));
                ui->label_statusSpeedFan_speed->setPixmap(QPixmap(":/icon/icons/speed.png"));
                ui->label_statusSpeedFan->setStyleSheet("QLabel{color:black;}");
            }
        }break;
        case HIM::label_alarm_watercooling : {
            if(it.value()>0){
                ui->label_alarm_watercooling->setPixmap(QPixmap(":/icon/icons/light_error.png"));
            }else{
                ui->label_alarm_watercooling->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
            }
        }break;
        case HIM::label_alarm_cabinDoor : {
            if(it.value()>0){
                ui->label_alarm_cabinDoor->setPixmap(QPixmap(":/icon/icons/light_error.png"));
            }else{
                ui->label_alarm_cabinDoor->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
            }
        }break;
        case HIM::label_alarm_O2 : {
            if(it.value()>0){
                ui->label_alarm_O2->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                ui->label_statusO2_o2->setPixmap(QPixmap(":/icon/icons/o2_err.png"));
                ui->label_statusO2->setStyleSheet("QLabel{color:red;}");
            }else{
                ui->label_alarm_O2->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_statusO2_o2->setPixmap(QPixmap(":/icon/icons/o2.png"));
                ui->label_statusO2->setStyleSheet("QLabel{color:black;}");
            }
        }break;
        case HIM::label_alarm_cabinPressure : {
            if(it.value()>0){
                ui->label_alarm_cabinPressure->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                ui->label_statusCabinPressure_pre->setPixmap(QPixmap(":/icon/icons/pressure_err.png"));
                ui->label_statusCabinPressure->setStyleSheet("QLabel{color:red;}");
            }else{
                ui->label_alarm_cabinPressure->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_statusCabinPressure_pre->setPixmap(QPixmap(":/icon/icons/pressure.png"));
                ui->label_statusCabinPressure->setStyleSheet("QLabel{color:black;}");
            }
        }break;
        case HIM::label_alarm_laser : {
            if(it.value()>0){
                ui->label_alarm_laser->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                ui->label_laserStatus_laser->setPixmap(QPixmap(":/icon/icons/laser_err.png"));
                ui->label_laserStatus->setStyleSheet("QLabel{color:red;}");
            }else{
                ui->label_alarm_laser->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_laserStatus_laser->setPixmap(QPixmap(":/icon/icons/laser.png"));
                ui->label_laserStatus->setStyleSheet("QLabel{color:black;}");
            }
        }break;
        case HIM::label_alarm_servoMan : {
            if(it.value()>0){
                ui->label_alarm_servoMan->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                QString errCode = "Err.";
                ui->label_servoErrCodeMan->setText(errCode.append(QString::number(it.value())));
                ui->label_servoErrCodeMan->setStyleSheet("QLabel{color:red;}");
                ui->label_statusServoMan_moto->setPixmap(QPixmap(":/icon/icons/moto_err.png"));
                HIM_ERROR("成型缸伺服故障报警：{}",it.value());
            }else{
                ui->label_alarm_servoMan->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_servoErrCodeMan->setText(tr("No Errors"));
                ui->label_servoErrCodeMan->setStyleSheet("QLabel{color:black;}");
                ui->label_statusServoMan_moto->setPixmap(QPixmap(":/icon/icons/moto.png"));
            }
        }break;
        case HIM::label_alarm_servoFeed : {
            if(it.value()>0){
                ui->label_alarm_servoFeed->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                QString errCode = "Err.";
                ui->label_servoErrCodeFeed->setText(errCode.append(QString::number(it.value())));
                ui->label_servoErrCodeFeed->setStyleSheet("QLabel{color:red;}");
                ui->label_statusServoFeed_moto->setPixmap(QPixmap(":/icon/icons/moto_err.png"));
                HIM_ERROR("供粉缸伺服故障报警：{}",it.value());
            }else{
                ui->label_alarm_servoFeed->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_servoErrCodeFeed->setText(tr("No Errors"));
                ui->label_servoErrCodeFeed->setStyleSheet("QLabel{color:black;}");
                ui->label_statusServoFeed_moto->setPixmap(QPixmap(":/icon/icons/moto.png"));
            }
        }break;
        case HIM::label_alarm_servoPow : {
            if(it.value()>0){
                ui->label_alarm_servoPow->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                QString errCode = "Err.";
                ui->label_servoErrCodePow->setText(errCode.append(QString::number(it.value())));
                ui->label_servoErrCodePow->setStyleSheet("QLabel{color:red;}");
                ui->label_statusServoPowder_moto->setPixmap(QPixmap(":/icon/icons/moto_err.png"));
                HIM_ERROR("刮刀伺服故障报警：{}",it.value());
            }else{
                ui->label_alarm_servoPow->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_servoErrCodePow->setText(tr("No Errors"));
                ui->label_servoErrCodePow->setStyleSheet("QLabel{color:black;}");
                ui->label_statusServoPowder_moto->setPixmap(QPixmap(":/icon/icons/moto.png"));
            }
        }break;
        case HIM::label_alarm_EnvTemp : {
            if(it.value()>0){
                ui->label_alarm_EnvTemp->setPixmap(QPixmap(":/icon/icons/light_error.png"));
                ui->label_statusEnvTemperature_temp->setPixmap(QPixmap(":/icon/icons/temperature_err.png"));
                ui->label_statusEnvTemperature->setStyleSheet("QLabel{color:red;}");
            }else{
                ui->label_alarm_EnvTemp->setPixmap(QPixmap(":/icon/icons/light_nomal.png"));
                ui->label_statusEnvTemperature_temp->setPixmap(QPixmap(":/icon/icons/temperature.png"));
                ui->label_statusEnvTemperature->setStyleSheet("QLabel{color:black;}");
            }
        }break;
        case HIM::label_statusairsupplyvalve : {
            ui->label_statusairsupplyvalve->setText(QString::number(it.value(),'f',2));
            ui->label_cp_4->setText(QString::number(it.value(),'f',2));
        }break;
        case HIM::label_statusCabinPressure : {
            ui->label_statusCabinPressure->setText(QString::number(it.value(),'f',2));

            if(plotRefresh){
                plotPressure_->drawPlot(time,it.value());
                plotPressureM_->drawPlot(time,it.value());
            }

        }break;
        case HIM::label_statusWashingvalvePressure : {
            ui->label_statusWashingvalvePressure->setText(QString::number(it.value(),'f',2));
            ui->label_cp_5->setText(QString::number(it.value(),'f',2));

        }break;
        case HIM::label_statusO2 : {
            ui->label_statusO2->setText(QString::number(it.value(),'f',2));
            ui->label_cp_1->setText(QString::number(it.value(),'f',2));

            if(plotRefresh){
                plotO2_->drawPlot(time,it.value());
                plotO2M_->drawPlot(time,it.value());
            }

        }break;
        case HIM::label_statsusAirO2 : {
            ui->label_statsusAirO2->setText(QString::number(it.value(),'f',2));
        }break;
        case HIM::label_statusBaseTemperature : {
            ui->label_statusBaseTemperature->setText(QString::number(it.value(),'f',2));
            ui->label_BaseCurrentTemp->setText(QString::number(it.value(),'f',2));

            if(plotRefresh){
                plotTemp_->drawPlot(0,time,it.value());
                plotTempM_->drawPlot(0,time,it.value());
            }

        }break;
        case HIM::label_statusEnvTemperature : {
            ui->label_statusEnvTemperature->setText(QString::number(it.value(),'f',2));

            if(plotRefresh){
                plotTemp_->drawPlot(1,time,it.value());
                plotTempM_->drawPlot(1,time,it.value());
            }

        }break;
        case HIM::label_cp_3 : {
            ui->label_cp_3->setText(QString::number(it.value(),'f',2));

            if(plotRefresh){
                plotMicroPressure_->drawPlot(time,it.value());
                plotMicroPressure_->drawPlot(time,it.value());
            }
        }break;
        case HIM::label_statusSpeedFan : {
            ui->label_statusSpeedFan->setText(QString::number(it.value(),'f',2));
            ui->label_cp_6->setText(QString::number(it.value(),'f',2));
        }break;
        case HIM::label_cp_2 : {
            ui->label_cp_2->setText(QString::number(it.value(),'f',2));
        }break;
        case HIM::label_cp_7 : {
            ui->label_cp_7->setText(QString::number(it.value(),'f',2));
        }break;
        case HIM::label_cp_8 : {
            ui->label_cp_8->setText(QString::number(it.value(),'f',2));
        }break;
        case HIM::label_cp_9 : {
            ui->label_cp_9->setText(QString::number(it.value(),'f',2));
        }break;
        case HIM::label_loopCleanStatus : {
            if(it.value()>0){
                TASKAGENT.setScrubbing(true);
                HIM_INFO(tr("Gas washing completed").toStdString());
                QMessageBox::information(this, tr("Tips"),
                                         tr("Gas washing completed"),
                                         QMessageBox::Yes);
            }
        }break;
        case HIM::label_laserStatus : {
            //TODO 同步激光状态


        }break;
        case HIM::label_statusServoPowder : {
            float pos = it.value();
            ui->label_servoPosScraper->setText(QString::number(pos,'f',3));
            ui->label_statusServoPowder->setText(QString::number(pos,'f',3));
        }break;
        case HIM::label_statusServoFeed : {
            float pos = it.value();
            ui->label_servoPosFeed->setText(QString::number(pos,'f',3));
            ui->label_statusServoFeed->setText(QString::number(pos,'f',3));
        }break;
        case HIM::label_statusServoMan : {
            float pos = it.value();
            ui->label_servoPosMan->setText(QString::number(pos,'f',3));
            ui->label_statusServoMan->setText(QString::number(pos,'f',3));
        }break;
        case HIM::pushButton_servoManufactureEnable : {
            if(it.value()>0){
                QSignalBlocker blocker(ui->pushButton_servoManufactureEnable);
                ui->pushButton_servoManufactureEnable->setText(tr("Disenable"));
                ui->pushButton_servoManufactureEnable->setCheckable(true);
                ui->pushButton_servoManufactureEnable->setChecked(true);
            }else{
                QSignalBlocker blocker(ui->pushButton_servoManufactureEnable);
                ui->pushButton_servoManufactureEnable->setText(tr("Enable"));
                ui->pushButton_servoManufactureEnable->setChecked(false);
                ui->pushButton_servoManufactureEnable->setCheckable(false);
            }
        }break;
        case HIM::pushButton_servoFeedEnable : {
            if(it.value()>0){
                QSignalBlocker blocker(ui->pushButton_servoFeedEnable);
                ui->pushButton_servoFeedEnable->setText(tr("Disenable"));
                ui->pushButton_servoFeedEnable->setCheckable(true);
                ui->pushButton_servoFeedEnable->setChecked(true);
            }else{
                QSignalBlocker blocker(ui->pushButton_servoFeedEnable);
                ui->pushButton_servoFeedEnable->setText(tr("Enable"));
                ui->pushButton_servoFeedEnable->setChecked(false);
                ui->pushButton_servoFeedEnable->setCheckable(false);
            }
        }break;
        case HIM::pushButton_servoPowderEnable : {
            if(it.value()>0){
                QSignalBlocker blocker(ui->pushButton_servoPowderEnable);
                ui->pushButton_servoPowderEnable->setText(tr("Disenable"));
                ui->pushButton_servoPowderEnable->setCheckable(true);
                ui->pushButton_servoPowderEnable->setChecked(true);
            }else{
                QSignalBlocker blocker(ui->pushButton_servoPowderEnable);
                ui->pushButton_servoPowderEnable->setText(tr("Enable"));
                ui->pushButton_servoPowderEnable->setChecked(false);
                ui->pushButton_servoPowderEnable->setCheckable(false);
            }
        }break;
        default:break;
        }
    }
}

void Monitor::on_updataCliShow(int layindex)
{
    ui->horizontalSlider_layer->setValue(layindex);
    osgWidget_->getOsgWidget()->getOsgViewer()->home();
    QPixmap osgCurunt = ui->frame_osg->grab();
    ui->label_print->setPixmap(osgCurunt);
    double progressValue = (double)layindex / (double)ui->horizontalSlider_layer->maximum();
    ui->progressBar_print->setValue(progressValue*100);
    ui->label_CurrentLevel->setText(QString::number(layindex));
}

void Monitor::on_printFinished()
{
    //TODO 打印完成后操作
    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_14,false);
    HIM_INFO(tr("print finished").toStdString());
    //TODO 生成打印报告和数据曲线记录 存储到数据库中调用
}

/***print function***/
void Monitor::on_pushButton_PrintStart_clicked()
{
    if(SYSTEMMONITOR.getSysStatus() == HIM::SYS_ERR){
        QMessageBox::warning(this, tr("Error"),
                             tr("The device status is abnormal, please check!"),
                             QMessageBox::Yes);
        return;
    }

    if(!CLIREAD.getCliLoaded()){
        QMessageBox::warning(this, tr("Error"),
                             tr("Slice file not loaded!"),
                             QMessageBox::Yes);
        return;
    }


    if(!SYSTEMMONITOR.getServosEnable()){
        QMessageBox::warning(this, tr("Error"),
                             tr("Servos is disenable!"),
                             QMessageBox::Yes);
        return;
    }

    if(TASKAGENT.getIsTaskWork())
    {
        TASKAGENT.startPrintTask();
        ui->toolButton_deviceStatus->setText(tr("Printing"));
    }else{
        int ret = QMessageBox::question(this, tr("Warning"),
                                        tr("Please clean the ash bucket first, the ash bucket cleaning countdown will be reset."),
                                        QMessageBox::Yes | QMessageBox::No);
        if(ret==QMessageBox::Yes){
            switch (TASKAGENT.checkPrintReady()) {
            case 0 :{
                QMessageBox::warning(this, tr("Error"),
                                     tr("The powder laying, substrate heating, and gas washing are not completed!"),
                                     QMessageBox::Yes);
            }break;
            case 1 :{
                QMessageBox::warning(this, tr("Error"),
                                     tr("The powder laying are not completed!"),
                                     QMessageBox::Yes);
            }break;
            case 2 :{
                QMessageBox::warning(this, tr("Error"),
                                     tr("The substrate heating are not completed!"),
                                     QMessageBox::Yes);
            }break;
            case 4 :{
                QMessageBox::warning(this, tr("Error"),
                                     tr("The gas washing are not completed!"),
                                     QMessageBox::Yes);
            }break;
            case 3 :{
                QMessageBox::warning(this, tr("Error"),
                                     tr("The powder laying and substrate heating are not completed!"),
                                     QMessageBox::Yes);
            }break;
            case 5 :{
                QMessageBox::warning(this, tr("Error"),
                                     tr("The powder laying and gas washing are not completed!"),
                                     QMessageBox::Yes);
            }break;
            case 6 :{
                QMessageBox::warning(this, tr("Error"),
                                     tr("The substrate heating and gas washing are not completed!"),
                                     QMessageBox::Yes);
            }break;
            case 7 :{
                //TODO 打印开始保护屏蔽

                plotTemp_->clearPlot();
                plotPressure_->clearPlot();
                plotO2_->clearPlot();
                plotTempM_->clearPlot();
                plotPressureM_->clearPlot();
                plotO2M_->clearPlot();
                plotMicroPressure_->clearPlot();

                int selectLayer = ui->spinBox_adjSelectPrintLayer->value();

                if(CLIREAD.getCurruntLayerIndex()!=selectLayer)
                    ui->horizontalSlider_layer->setValue(selectLayer);

                osgWidget_->getOsgWidget()->getOsgViewer()->home();
                QPixmap osgCurunt = ui->frame_osg->grab();
                ui->label_print->setPixmap(osgCurunt);

                ui->toolButton_deviceStatus->setIcon(QIcon(":/icon/icons/lamp_work.png"));
                ui->toolButton_deviceStatus->setText(tr("Printing"));

                QDateTime current = QDateTime::currentDateTime();
                ui->label_PrintStartTime->setText(current.toString("yyyy-MM-dd hh:mm"));
                QDateTime endPrintTime = current.addSecs(CLIREAD.getPrintEstimatedTime());
                ui->label_ExpectedEndTime->setText(endPrintTime.toString("yyyy-MM-dd hh:mm"));

                ui->label_totalLayers->setText(QString::number(CLIREAD.getCliHeasderData()->layers));
                ui->label_CurrentLevel->setText(QString::number(selectLayer));

                PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_14,true);
                TASKAGENT.startPrintTask();
                printProtect();
            }break;
            default:break;
            }
        }
    }
}

void Monitor::printProtect()
{
    ui->pushButton_adjSelectPrintLayer->setDisabled(true);
    ui->spinBox_adjSelectPrintLayer->setDisabled(true);
}

void Monitor::printEnd()
{
    ui->pushButton_adjSelectPrintLayer->setDisabled(false);
    ui->spinBox_adjSelectPrintLayer->setDisabled(false);

    ui->spinBox_adjSelectPrintLayer->setValue(1);

}

void Monitor::on_pushButton_PrintPaused_clicked()
{
    if(TASKAGENT.pausePrintTask())
        ui->toolButton_deviceStatus->setText(tr("Print Paused"));
}

void Monitor::on_pushButton_PrintTermination_clicked()
{
    if(TASKAGENT.getIsTaskWork()){
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_14,false);
        TASKAGENT.stopPrintTask();
        QMessageBox::warning(this, tr("Print termination"),
                             tr("User termination!"),
                             QMessageBox::Yes);

        ui->toolButton_deviceStatus->setIcon(QIcon(":/icon/icons/lamp_idle.png"));
        ui->toolButton_deviceStatus->setText(tr("normal"));
        printEnd();
    }
}

/***connect function***/
void Monitor::on_pushButton_oneReconnection_clicked()
{
    SYSTEMMONITOR.connectAll();
}

void Monitor::on_pushButton_alarmResetAll_clicked()
{
    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_11,true);
    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_11,false);

    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V76_9,true);
    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V76_9,false);
}

/***load sysconfig function***/
bool Monitor::loadSysConfig()
{
    try {
        if(SYSTEMCONFIG.loadfile(CONFIGPATH)){
            return true;
        }else{
            return false;
        }
    } catch (std::exception & e) {
        HIM_ERROR("updata parameter error {}",e.what());
        return false;
    }
}

void Monitor::onSysConfigChanged(int value)
{
    Q_UNUSED(value);
    try {
        QSpinBox *senderObj= qobject_cast<QSpinBox*>(sender());
        if(senderObj == nullptr)
            return;
        senderObj->setStyleSheet("QSpinBox { color: red; }");
    } catch (std::exception & e) {
        HIM_ERROR("set SpinBox parameter error {}",e.what());
    }
}

void Monitor::onSysConfigChanged(double value)
{
    Q_UNUSED(value);
    try {
        QDoubleSpinBox *senderObj= qobject_cast<QDoubleSpinBox*>(sender());
        if(senderObj == nullptr)
            return;
        senderObj->setStyleSheet("QDoubleSpinBox { color: red; }");
    } catch (std::exception & e) {
        HIM_ERROR("set DoubleSpinBox parameter error {}",e.what());
        return;
    }
}

void Monitor::onSysConfigChanged(const QString & value)
{
    Q_UNUSED(value);
    try {
        QComboBox *senderObj= qobject_cast<QComboBox*>(sender());
        if(senderObj == nullptr)
            return;
        senderObj->setStyleSheet("QComboBox { color: red; }");
    } catch (std::exception & e) {
        HIM_ERROR("set ComboBox parameter error {}",e.what());
        return;
    }
}

void Monitor::onSysConfigChangedLineEdit(const QString & value)
{
    Q_UNUSED(value);
    try {
        QLineEdit *senderObj= qobject_cast<QLineEdit*>(sender());
        if(senderObj == nullptr)
            return;
        senderObj->setStyleSheet("QLineEdit { color: red; }");
    } catch (std::exception & e) {
        HIM_ERROR("set LineEdit parameter error {}",e.what());
        return;
    }
}

/***slice function***/
void Monitor::on_pushButton_open_clicked()
{
    try{
        QString filePath = QFileDialog::getOpenFileName(
                    this, tr("Select a slice file"), "../data/cli/", tr("CLI Files (*.cli)"),nullptr,QFileDialog::ReadOnly);
        qDebug()<<"open file path:"<<filePath;

        if(filePath!=NULL){
            if(CLIREAD.readCLIFile(filePath)){
                int date = CLIREAD.getCliHeasderData()->date;
                int labels = CLIREAD.getCliHeasderData()->label.size();
                int layers = CLIREAD.getCliHeasderData()->layers;
                float zPos = CLIREAD.getCliCurruntLayerData()->zPos;
                double high = CLIREAD.getCliHeasderData()->layers*zPos;
                double printEstimatedTime = CLIREAD.getPrintEstimatedTime();

                QFileInfo fileInfo(filePath);
                ui->lineEdit_FileName->setText(fileInfo.fileName());
                ui->label_cliFileName->setText(fileInfo.fileName());
                ui->lineEdit_CliDate->setText(QString::number(date));
                ui->lineEdit_CliLabers->setText(QString::number(labels));
                ui->lineEdit_CliLayers->setText(QString::number(layers));
                ui->lineEdit_LayerHigh->setText(QString::number(zPos));                

                TASKAGENT.setLayerHigh(zPos);

                ui->lineEdit_CliHigh->setText(QString::number(high));
                ui->lineEdit_CliPrintEstimatedTime->setText(QString::number((printEstimatedTime/3600.),'f',2));
                ui->horizontalSlider_layer->setMaximum(layers-2);
                ui->horizontalSlider_layer->setValue(1);
                ui->spinBox_adjSelectPrintLayer->setValue(1);
                ui->tableWidget_CliLabers->setRowCount(labels);
                ui->tableWidget_CliLabers->setColumnCount(2);

                for (int i = 0; i < labels ; i++){
                    ui->tableWidget_CliLabers->setItem(i,0,new QTableWidgetItem(""));
                    ui->tableWidget_CliLabers->item(i,0)->setFlags(Qt::ItemIsEditable);
                }

                int j = 0 ;
                for(auto i : CLIREAD.getCliHeasderData()->label){
                    QCheckBox *laberSelect = new QCheckBox(this);
                    //laberSelect->setText(i.second);
                    laberSelect->setProperty("index",i.first);
                    laberSelect->setChecked(true);
                    connect(laberSelect, SIGNAL(stateChanged(int)), this, SLOT(onCliLaberSelectStateChanged(int)));
                    ui->tableWidget_CliLabers->setCellWidget(j,0,laberSelect);
                    QTableWidgetItem *item = new QTableWidgetItem(i.second);
                    ui->tableWidget_CliLabers->setItem(j, 1, item);
                    j++;
                }

                ui->tableWidget_CliLabers->resizeColumnToContents(0);
                ui->tableWidget_CliLabers->resizeColumnToContents(1);

                QMap<int,QVector<QPair<QPointF,QPointF>>> sliceNodeData;

                for(auto i : CLIREAD.getCliCurruntLayerData()->hatchesList){
                    sliceNodeData[i.label].append(i.hatchVector);
                }

                osgWidget_->getOsgWidget()->getOsgViewer()->home();
                OSGDATAMANAGER->getSliceNode("SliceData")->updataSliceNode(zPos,sliceNodeData);
                QPixmap osgCurunt = ui->frame_osg->grab();
                ui->label_print->setPixmap(osgCurunt);
            }
        }else{
            HIM_INFO("No file selected");
        }
    }catch(std::exception& e){
        HIM_ERROR("read cli file fali:{}",e.what());
    }
}

void Monitor::on_pushButton_save_clicked()
{
    //TODO 解析好的文件可以保存  加速下次解析
}

void Monitor::onCliLaberSelectStateChanged(int state)
{
    QCheckBox *senderObj=qobject_cast<QCheckBox*>(sender());
    if(senderObj == nullptr)
        return;

    //TODO 优化选择跳过
    if(state>0){
        TASKAGENT.deleteSkipIndexs(senderObj->property("index").toInt());
    }else{
        TASKAGENT.addSkipIndexs(senderObj->property("index").toInt());
    }

    QSet<int> skipIndexs = TASKAGENT.getSkipIndexs();
    int value = ui->horizontalSlider_layer->value();

    CLIREAD.analysisCLILayer(value);
    float zPos = CLIREAD.getCliCurruntLayerData()->zPos;
    QMap<int,QVector<QPair<QPointF,QPointF>>> sliceNodeData;
    for(auto i : CLIREAD.getCliCurruntLayerData()->hatchesList){
        if(!skipIndexs.contains(i.label)){
            sliceNodeData[i.label].append(i.hatchVector);
        }
    }
    OSGDATAMANAGER->getSliceNode("SliceData")->updataSliceNode(zPos,sliceNodeData);
    qDebug()<<"index :"<<senderObj->property("index").toInt()<<"state:"<<state ;
}

void Monitor::on_horizontalSlider_layer_valueChanged(int value)
{
    ui->label_layerCurr->setText(QString::number(value));
    //TODO 转到task里面做
    QSet<int> skipIndexs = TASKAGENT.getSkipIndexs();

    CLIREAD.analysisCLILayer(value);
    float zPos = CLIREAD.getCliCurruntLayerData()->zPos;
    QMap<int,QVector<QPair<QPointF,QPointF>>> sliceNodeData;
    for(auto i : CLIREAD.getCliCurruntLayerData()->hatchesList){
        if(!skipIndexs.contains(i.label)){
            sliceNodeData[i.label].append(i.hatchVector);
        }
    }
    OSGDATAMANAGER->getSliceNode("SliceData")->updataSliceNode(zPos,sliceNodeData);
}

void Monitor::on_pushButton_layerSubtraction_clicked()
{
    int value = ui->horizontalSlider_layer->value();
    if(value != ui->horizontalSlider_layer->minimum()){
        ui->horizontalSlider_layer->setValue(value-1);
    }
}

void Monitor::on_pushButton_layerAdd_clicked()
{
    int value = ui->horizontalSlider_layer->value();
    if(value != ui->horizontalSlider_layer->maximum()){
        ui->horizontalSlider_layer->setValue(value+1);
    }
}

/***servo function***/
void Monitor::on_toolButton_setServoJog1um_clicked()
{
    try{
        SERVOAGENT.setJogUnitDis(1);
    }catch(std::exception& e){
        string errStr = "Set servo jog 1 um err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_toolButton_setServoJog10um_clicked()
{
    try{
        SERVOAGENT.setJogUnitDis(10);
    }catch(std::exception& e){
        string errStr = "Set servo jog 10 um err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_toolButton_setServoJog25um_clicked()
{
    try{
        SERVOAGENT.setJogUnitDis(25);
    }catch(std::exception& e){
        string errStr = "Set servo jog 25 um err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_toolButton_setServoJog100um_clicked()
{
    try{
        SERVOAGENT.setJogUnitDis(100);
    }catch(std::exception& e){
        string errStr = "Set servo jog 100 um err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_toolButton_setServoJog1mm_clicked()
{
    try{
        SERVOAGENT.setJogUnitDis(1000);
    }catch(std::exception& e){
        string errStr = "Set servo jog 1000 um err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_toolButton_ServoAJogUp_clicked()
{
    try{
        double speed = ui->doubleSpinBox_ServoASpeed->value();
        SERVOAGENT.moveJog(MANUFACTURE,UP,speed);
    }catch(std::exception& e){
        string errStr = "Servo MANUFACTURE jog up err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_toolButton_ServoAJogDown_clicked()
{
    try{
        double speed = ui->doubleSpinBox_ServoASpeed->value();
        SERVOAGENT.moveJog(MANUFACTURE,DOWN,speed);
    }catch(std::exception& e){
        string errStr = "Servo MANUFACTURE jog down err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_ServoAPosMove_clicked()
{
    try{
        double speed = ui->doubleSpinBox_ServoASpeed->value();
        double pos = ui->doubleSpinBox_ServoAPos->value();
        SERVOAGENT.moveAbs(MANUFACTURE,pos,speed);
    }catch(std::exception& e){
        string errStr = "Servo MANUFACTURE pos move err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_ServoAGo0_clicked()
{
    try{
        double speed = ui->doubleSpinBox_ServoASpeed->value();
        SERVOAGENT.moveZero(MANUFACTURE,speed);
    }catch(std::exception& e){
        string errStr = "Servo MANUFACTURE go zero err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_ServoASet0_clicked()
{
    try{
        SERVOAGENT.setZero(MANUFACTURE);
    }catch(std::exception& e){
        string errStr = "Servo MANUFACTURE set zero err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_toolButton_ServoBJogUp_clicked()
{
    try{
        double speed = ui->doubleSpinBox_ServoBSpeed->value();
        SERVOAGENT.moveJog(FEED,UP,speed);
    }catch(std::exception& e){
        string errStr = "Servo FEED jog up err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_toolButton_ServoBJogDown_clicked()
{
    try{
        double speed = ui->doubleSpinBox_ServoBSpeed->value();
        SERVOAGENT.moveJog(FEED,DOWN,speed);
    }catch(std::exception& e){
        string errStr = "Servo FEED jog down err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_ServoBPosMove_clicked()
{
    try{
        double speed = ui->doubleSpinBox_ServoBSpeed->value();
        double pos = ui->doubleSpinBox_ServoBPos->value();
        SERVOAGENT.moveAbs(FEED,pos,speed);
    }catch(std::exception& e){
        string errStr = "Servo FEED pos move err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_ServoBGo0_clicked()
{
    try{
        double speed = ui->doubleSpinBox_ServoBSpeed->value();
        SERVOAGENT.moveZero(FEED,speed);
    }catch(std::exception& e){
        string errStr = "Servo FEED go zero err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_ServoBSet0_clicked()
{
    try{
        SERVOAGENT.setZero(FEED);
    }catch(std::exception& e){
        string errStr = "Servo FEED set zero err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_servoPowderEnable_clicked()
{
    try{
        if(ui->pushButton_servoPowderEnable->isCheckable()){
            SERVOAGENT.servoDisEnable(POWDER);
        }else{
            SERVOAGENT.servoEnable(POWDER);
        }
    }catch(std::exception& e){
        string errStr = "Servo POWDER enable err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_servoFeedEnable_clicked()
{
    try{
        if(ui->pushButton_servoFeedEnable->isCheckable()){
            SERVOAGENT.servoDisEnable(FEED);
        }else{
            SERVOAGENT.servoEnable(FEED);
        }
    }catch(std::exception& e){
        string errStr = "Servo Feed enable err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_servoManufactureEnable_clicked()
{
    try{
        if(ui->pushButton_servoManufactureEnable->isCheckable()){
            SERVOAGENT.servoDisEnable(MANUFACTURE);
        }else{
            SERVOAGENT.servoEnable(MANUFACTURE);
        }
    }catch(std::exception& e){
        string errStr = "Servo MANUFACTURE enable err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_servoManufactureStop_clicked()
{
    try{
        SERVOAGENT.moveStop(MANUFACTURE);
    }catch(std::exception& e){
        string errStr = "Servo MANUFACTURE stop err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_servoFeedStop_clicked()
{
    try{
        SERVOAGENT.moveStop(FEED);
    }catch(std::exception& e){
        string errStr = "Servo Feed stop err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_scraperPosMove_clicked()
{
    try{
        double speed = ui->doubleSpinBox_scraperSpeed->value();
        double pos = ui->doubleSpinBox_scraperPos->value();
        SERVOAGENT.moveAbs(POWDER,pos,speed);
    }catch(std::exception& e){
        string errStr = "Servo POWDER pos move err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_scraperPosStop_clicked()
{
    try{
        SERVOAGENT.moveStop(POWDER);
    }catch(std::exception& e){
        string errStr = "Servo POWDER stop err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_scraperGo0_clicked()
{
    try{
        double speed = ui->doubleSpinBox_scraperSpeed->value();
        SERVOAGENT.moveZero(POWDER,speed);
    }catch(std::exception& e){
        string errStr = "Servo POWDER go zero err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_scraperSet0_clicked()
{
    try{
        SERVOAGENT.setZero(POWDER);
    }catch(std::exception& e){
        string errStr = "Servo POWDER set zero err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_servoManufactureReset_clicked()
{
    try{
        SERVOAGENT.servoReset(MANUFACTURE);
    }catch(std::exception& e){
        string errStr = "Servo MANUFACTURE stop err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_servoFeedReset_clicked()
{
    try{
        SERVOAGENT.servoReset(FEED);
    }catch(std::exception& e){
        string errStr = "Servo FEED reset err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_servoPowderReset_clicked()
{
    try{
        SERVOAGENT.servoReset(POWDER);
    }catch(std::exception& e){
        string errStr = "Servo POWDER reset err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_scraperMoveLeft_clicked()
{
    try{
        double speed = ui->doubleSpinBox_scraperCoverSpeed->value();
        SERVOAGENT.scraperMoveLeft(speed);
    }catch(std::exception& e){
        string errStr = "Servo POWDER Move Left err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}

void Monitor::on_pushButton_scraperMoveRight_clicked()
{
    try{
        double speed = ui->doubleSpinBox_scraperSpeed->value();
        SERVOAGENT.scraperMoveRight(speed);
    }catch(std::exception& e){
        string errStr = "Servo POWDER Move Left err:";
        HIM_ERROR(errStr.append(e.what()));
    }
}


//void Monitor::on_pushButton_testSave_clicked()
//{
//    try {
//        auto fileName = "../data/test.ini";

//        QObjectList objectList = ui->tab_systemSet->children();
//        objectList.append(ui->tab_ConnectSet->children());
//        objectList.append(ui->tab_ServoSet->children());
//        objectList.append(ui->tab_LaserSet->children());

//        for(auto it : objectList){
//            if(it->metaObject()->className()==QString("QSpinBox")){
//                SYSTEMCONFIG.setLongValue(PARAMETER,it->objectName().toStdString(), dynamic_cast<QSpinBox*>(it)->value());
//            }else if(it->metaObject()->className()==QString("QDoubleSpinBox")){
//                SYSTEMCONFIG.setDoubleValue(PARAMETER,it->objectName().toStdString(),dynamic_cast<QDoubleSpinBox*>(it)->value());
//            }else if(it->metaObject()->className()==QString("QComboBox")){
//                SYSTEMCONFIG.setValue(PARAMETER,it->objectName().toStdString(),dynamic_cast<QComboBox*>(it)->currentText().toStdString());
//            }else if(it->metaObject()->className()==QString("QLineEdit")){
//                SYSTEMCONFIG.setValue(PARAMETER,it->objectName().toStdString(),dynamic_cast<QLineEdit*>(it)->text().toStdString());
//            }
//        }

//        if(!SYSTEMCONFIG.saveFile(fileName))
//            HIM_ERROR("save file {} error.",fileName);

//    } catch (std::exception & e) {
//        HIM_ERROR("save parameter to {} error.",e.what());
//    }
//}



void Monitor::on_pushButton_StartPreheating_clicked(bool checked)
{
    //TODO 改为PLC通讯修改按钮状态
    if(checked){
        float baseTemp = ui->doubleSpinBox_BaseTemperature->value();
        PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD72_0,baseTemp);
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V76_8,true);
        ui->doubleSpinBox_adjBaseTemp->setValue(baseTemp);
        TASKAGENT.setBaseHeating(true);
    }else{
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V76_8,false);
        TASKAGENT.setBaseHeating(false);
    }
}

//循环净化功能
void Monitor::on_pushButton_SetoxygenContent_clicked()
{
    float value = ui->doubleSpinBox_oxygenContent->value();
    PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD56_0,value);
    SYSTEMCONFIG.setDoubleValue(PARAMETER,"oxygenContent", value);
    SYSTEMCONFIG.saveFile(CONFIGPATH);
}

void Monitor::on_pushButton_SetoxygenContentMax_clicked()
{
    float value = ui->doubleSpinBox_oxygenContentMax->value();
    PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD60_0,value);
    SYSTEMCONFIG.setDoubleValue(PARAMETER,"oxygenContentMax", value);
    SYSTEMCONFIG.saveFile(CONFIGPATH);
}

void Monitor::on_pushButton_SetyAirRate_clicked()
{
    float value = ui->doubleSpinBox_AirRate->value();
    PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD64_0,value);
    SYSTEMCONFIG.setDoubleValue(PARAMETER,"AirRate", value);
    SYSTEMCONFIG.saveFile(CONFIGPATH);
}

void Monitor::on_pushButton_SetCabinPressureMax_clicked()
{
    float value = ui->doubleSpinBox_CabinPressureMax->value();
    PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD80_0,value);
    SYSTEMCONFIG.setDoubleValue(PARAMETER,"CabinPressureMax", value);
    SYSTEMCONFIG.saveFile(CONFIGPATH);
}

void Monitor::on_pushButton_SetCabinPressureMin_clicked()
{
    float value = ui->doubleSpinBox_CabinPressureMin->value();
    PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD84_0,value);
    SYSTEMCONFIG.setDoubleValue(PARAMETER,"CabinPressureMin", value);
    SYSTEMCONFIG.saveFile(CONFIGPATH);
}

void Monitor::on_pushButton_GasWashingStart_clicked(bool checked)
{
    //TODO
    //modify to plc read syn
    if(checked){
        HIM_INFO("Start gas wash");
        float value = ui->doubleSpinBox_oxygenContent->value();
        PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD56_0,value);
        value = ui->doubleSpinBox_oxygenContentMax->value();
        PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD60_0,value);
        value = ui->doubleSpinBox_AirRate->value();
        PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD64_0,value);
        ui->doubleSpinBox_adjLoopFanSpeed->setValue(value);
        value = ui->doubleSpinBox_CabinPressureMax->value();
        PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD80_0,value);
        value = ui->doubleSpinBox_CabinPressureMin->value();
        PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD84_0,value);
        ui->pushButton_GasWashingStart->setText(tr("Stop washing"));
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_10,true);
    }else{
        HIM_INFO("Stop gas wash");
        ui->pushButton_GasWashingStart->setText(tr("Start washing"));
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_10,false);
    }
}

void Monitor::on_pushButton_backblowingClean_clicked(bool checked)
{
    if(checked){
        HIM_INFO("Start backblowing Clean");
        ui->pushButton_backblowingClean->setText(tr("Stop blowing"));
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_12,true);
    }else{
        HIM_INFO("Stop backblowing Clean");
        ui->pushButton_backblowingClean->setText(tr("Start blowing"));
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_12,false);
    }
}

void Monitor::on_pushButton_PipelineCleaningStart_clicked(bool checked)
{
    if(checked){
        HIM_INFO("Start Pipeline Clean");
        ui->pushButton_PipelineCleaningStart->setText(tr("Stop pipe washing"));
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_13,true);
    }else{
        HIM_INFO("Stop Pipeline Clean");
        ui->pushButton_PipelineCleaningStart->setText(tr("Start pipe washing"));
        PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_13,false);
    }
}

void Monitor::on_pushButton_alarmReset_clicked()
{
    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_11,true);
    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V76_9,true);
}

void Monitor::on_pushButton_applyParaModify_clicked()
{
    try {
        QObjectList objectList;
        switch (ui->tabWidget_set->currentIndex()) {
        case 0 : {
            objectList = ui->tab_systemSet->children();
        }break;
        case 1 : {
            objectList = ui->tab_ServoSet->children();
        }break;
        case 2 : {
            objectList = ui->tab_LaserSet->children();
        }break;
        default:break;
        }

        for(auto it : objectList){
            if(it->metaObject()->className()==QString("QSpinBox")){
                SYSTEMCONFIG.setLongValue(PARAMETER,it->objectName().toStdString(), dynamic_cast<QSpinBox*>(it)->value());
                qobject_cast<QSpinBox*>(it)->setStyleSheet("QSpinBox { color: black; }");
            }else if(it->metaObject()->className()==QString("QDoubleSpinBox")){
                SYSTEMCONFIG.setDoubleValue(PARAMETER,it->objectName().toStdString(),dynamic_cast<QDoubleSpinBox*>(it)->value());
                qobject_cast<QDoubleSpinBox*>(it)->setStyleSheet("QDoubleSpinBox { color: black; }");
            }else if(it->metaObject()->className()==QString("QComboBox")){
                SYSTEMCONFIG.setValue(PARAMETER,it->objectName().toStdString(),dynamic_cast<QComboBox*>(it)->currentData().toString().toStdString());
                qobject_cast<QComboBox*>(it)->setStyleSheet("QComboBox { color: black; }");
            }else if(it->metaObject()->className()==QString("QLineEdit")){
                SYSTEMCONFIG.setValue(PARAMETER,it->objectName().toStdString(),dynamic_cast<QLineEdit*>(it)->text().toStdString());
                qobject_cast<QLineEdit*>(it)->setStyleSheet("QLineEdit { color: black; }");
            }
        }

        switch (ui->tabWidget_set->currentIndex()) {
        case 0 : {
            SYSTEMMONITOR.applySysParas();
        }break;
        case 1 : {
            SYSTEMMONITOR.applyServoParas();
        }break;
        case 2 : {
            SYSTEMMONITOR.applyLaserParas();
        }break;
        default:break;
        }

        if(!SYSTEMCONFIG.saveFile(CONFIGPATH))
            HIM_ERROR("save parameter to file {} error.",CONFIGPATH);

    } catch (std::exception & e) {
        HIM_ERROR("save system parameter error : {} .",e.what());
    }
}

void Monitor::on_pushButton_undoParaModify_clicked()
{
    try {
        QObjectList objectList;
        switch (ui->tabWidget_set->currentIndex()) {
        case 0 : {
            objectList = ui->tab_systemSet->children();
        }break;
        case 1 : {
            objectList = ui->tab_ServoSet->children();
        }break;
        case 2 : {
            objectList = ui->tab_LaserSet->children();
        }break;
        default:break;
        }

        for(auto it : objectList){
            if(it->metaObject()->className()==QString("QSpinBox")){
                auto value = SYSTEMCONFIG.getLongValue(PARAMETER,it->objectName().toStdString());
                QSignalBlocker blocker(dynamic_cast<QSpinBox*>(it));
                dynamic_cast<QSpinBox*>(it)->setValue(value);
                dynamic_cast<QSpinBox*>(it)->setStyleSheet("QSpinBox { color: black; }");
            }else if(it->metaObject()->className()==QString("QDoubleSpinBox")){
                auto value = SYSTEMCONFIG.getDoubleValue(PARAMETER,it->objectName().toStdString());
                QSignalBlocker blocker(dynamic_cast<QDoubleSpinBox*>(it));
                dynamic_cast<QDoubleSpinBox*>(it)->setValue(value);
                dynamic_cast<QDoubleSpinBox*>(it)->setStyleSheet("QDoubleSpinBox { color: black; }");
            }else if(it->metaObject()->className()==QString("QComboBox")){
                auto value = SYSTEMCONFIG.getValue(PARAMETER,it->objectName().toStdString());
                auto index = dynamic_cast<QComboBox*>(it)->findData(QString::fromStdString(value));
                if(-1!=index){
                    QSignalBlocker blocker(dynamic_cast<QComboBox*>(it));
                    dynamic_cast<QComboBox*>(it)->setCurrentIndex(index);
                    dynamic_cast<QComboBox*>(it)->setStyleSheet("QComboBox { color: black; }");
                }else{
                    SYSTEMCONFIG.setValue(PARAMETER,it->objectName().toStdString(),
                                          dynamic_cast<QComboBox*>(it)->currentData().toString().toStdString());
                    SYSTEMCONFIG.saveFile(CONFIGPATH);
                }
            }else if(it->metaObject()->className()==QString("QLineEdit")){
                auto value = SYSTEMCONFIG.getValue(PARAMETER,it->objectName().toStdString());
                QSignalBlocker blocker(dynamic_cast<QLineEdit*>(it));
                dynamic_cast<QLineEdit*>(it)->setText(QString::fromStdString(value));
                dynamic_cast<QLineEdit*>(it)->setStyleSheet("QLineEdit { color: black; }");
            }
        }

    } catch (std::exception & e) {
        HIM_ERROR(" undo parameter error : {}.",e.what());
    }
}

void Monitor::on_pushButton_adjBaseTemp_clicked()
{
    float baseTemp = ui->doubleSpinBox_adjBaseTemp->value();
    PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD72_0,baseTemp);
    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V76_8,true);
    ui->doubleSpinBox_adjBaseTemp->setValue(baseTemp);
}

void Monitor::on_pushButton_adjPowerRatio_clicked()
{
    TASKAGENT.setAdjPcMulValue(ui->doubleSpinBox_adjPowerRatio->value());
}

void Monitor::on_pushButton_adjLoopFanSpeed_clicked()
{
    float value = ui->doubleSpinBox_adjLoopFanSpeed->value();
    PLCDATAPROCESSER.addSetPlcFloatDataTask(HIM::SO_VD64_0,value);
}

void Monitor::on_pushButton_adjLaserPowerRatio_clicked()
{
    TASKAGENT.setAdjLaserPowerRatio(ui->doubleSpinBox_adjLaserPowerRatio->value());
}

void Monitor::on_pushButton_adjScraperSpeedRatio_clicked()
{   
    TASKAGENT.setAdjScraperSpeedRatio(ui->doubleSpinBox_adjScraperSpeedRatio->value());
}

void Monitor::on_pushButton_adjLaserSpeedRatio_clicked()
{
    TASKAGENT.setAdjLaserSpeedRatio(ui->doubleSpinBox_adjLaserSpeedRatio->value());
}

void Monitor::on_radioButton_spreadingOK_clicked(bool checked)
{
    TASKAGENT.setFirstPowderSpreaded(checked);
}

void Monitor::on_pushButton_adjSelectPrintLayer_clicked()
{
    int selectLayer = ui->spinBox_adjSelectPrintLayer->value();
    ui->horizontalSlider_layer->setValue(selectLayer);
    osgWidget_->getOsgWidget()->getOsgViewer()->home();
    QPixmap osgCurunt = ui->frame_osg->grab();
    ui->label_print->setPixmap(osgCurunt);
}

void Monitor::on_radioButton_CabinLighting_clicked(bool checked)
{
    PLCDATAPROCESSER.addSetPlcBitDataTask(HIM::SO_V52_6,checked);
}
